package cn.schoolwow.quickdao.module.database.dql.condition.flow.set;

import cn.schoolwow.quickdao.domain.provider.DatabaseProvider;
import cn.schoolwow.quickdao.module.database.dql.condition.flow.get.GetFromConditionStatement;
import cn.schoolwow.quickdao.module.database.dql.parent.domain.QueryContext;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;

import java.util.List;

public class SetFromTableFragmentFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        setByEntity(flowContext);
        setByFromCondition(flowContext);
    }

    @Override
    public String name() {
        return "设置查询表语句片段";
    }

    private void setByEntity(FlowContext flowContext){
        QueryContext queryContext = (QueryContext) flowContext.checkData("queryContext");
        boolean addTableAliasName = (boolean) flowContext.checkData("addTableAliasName");
        DatabaseProvider databaseProvider = flowContext.checkInstanceData(DatabaseProvider.class);

        if(null!=queryContext.queryOption.queryTableOption.entity){
            flowContext.remark("根据表名设置");
            String tableName = queryContext.queryOption.queryTableOption.entity.tableName;
            //虚拟表不需要转义表名
            if("dual".equalsIgnoreCase(queryContext.queryOption.queryTableOption.entity.tableName)){
                queryContext.from = " from dual";
            }else{
                queryContext.from = " from " + databaseProvider.escape(tableName) + (addTableAliasName?" as "+databaseProvider.escape(queryContext.queryOption.queryTableOption.tableAliasName):"");
            }
        }
    }

    private void setByFromCondition(FlowContext flowContext){
        QueryContext queryContext = (QueryContext) flowContext.checkData("queryContext");

        if(null!=queryContext.queryOption.queryTableOption.fromCondition){
            flowContext.remark("根据子查询设置");
            FlowContext fromConditionFlowContext = flowContext.getQuickFlow().startFlow(new GetFromConditionStatement())
                    .putTemporaryData("fromCondition", queryContext.queryOption.queryTableOption.fromCondition)
                    .execute();

            String fromConditionStatement = (String) fromConditionFlowContext.checkData("fromConditionStatement");
            queryContext.from = " from (" + fromConditionStatement + ") " + queryContext.queryOption.queryTableOption.tableAliasName;
            queryContext.fromParameters = (List<Object>) fromConditionFlowContext.getData("fromConditionParameters");
        }
    }

}
